import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import Cookies from 'js-cookie';

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      name: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim();
        const password = userInfo.password;
        return new Promise((resolve, reject) => {
          login(username, password).then(res => {
            if (res.code == 200) {
              const data = res.result;
              setToken(data.token);
              this.token = data.token;
              Cookies.set("user_id", data.id);
            }
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        const id = Cookies.get("user_id");
        return new Promise((resolve, reject) => {
          getInfo(id).then(res => {
            res = res.result;
            res["permissions"] = [ "*:*:*" ];
            res["roles"] = [res.type];
            res.user = {
              "remark": res.type == "admin" ? "管理员" : "用户",
              "userId": res.id,
              "admin": true
            }
            const user = res.user;
            const avatar = (user.avatar == "" || user.avatar == null) ? defAva : user.avatar;

            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.name = user.userName
            this.avatar = avatar;
            
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useUserStore
